package cn.kjcoder.redis.controller;

import cn.kjcoder.redis.domain.CartPage;
import cn.kjcoder.redis.domain.CookieCart;
import cn.kjcoder.redis.service.IdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static cn.kjcoder.redis.controller.UserCartController.CART_KEY;

/**
 * @author hkj
 * @email 1349091387@qq.com
 * @date 2022/1/20
 * 源码允许修改，并且本人十分乐意有 大佬 来对代码进行 随 意 调 教
 **/
@RestController
@Slf4j
@RequestMapping("/cookCart")
public class CookieCartController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    public static final String COOKIE_KEY = "cart:cookie:";

    /**
     * 添加购物车
     */
    @PostMapping("/addCart")
    public void addCart(CookieCart cookieCart){
        String cartId = this.getCookiesCartId();
        String key = COOKIE_KEY + cartId;
        Boolean hasKey = this.redisTemplate.opsForHash().getOperations().hasKey(key);
        if(hasKey){
            this.redisTemplate.opsForHash().put(key,cookieCart.getProductId().toString(),cookieCart.getAmount());
        }else{
            this.redisTemplate.opsForHash().put(key,cookieCart.getProductId().toString(),cookieCart.getAmount());
            this.redisTemplate.expire(key,90, TimeUnit.DAYS);
        }
    }

    /**
     * 修改购物车商品数量
     */
    @PostMapping("/updateCart")
    public void updateCart(CookieCart cookieCart){
        String cartId = this.getCookiesCartId();
        String key = COOKIE_KEY + cartId;
        this.redisTemplate.opsForHash().put(key,cookieCart.getProductId().toString(),cookieCart.getAmount());
    }

    /**
     *删除购物车商品
     */
    @PostMapping("/deleteCart")
    public void deleteCart(Long productId){
        String cartId = this.getCookiesCartId();
        String key = COOKIE_KEY + cartId;
        this.redisTemplate.opsForHash().delete(key,productId.toString());
    }

    /**
     * 查询所有购物车商品
     */
    @PostMapping("/findAll")
    public CartPage findAll(){
        String cartId = this.getCookiesCartId();
        String key = COOKIE_KEY + cartId;
        CartPage<CookieCart> cartPage = new CartPage();
        //查询购物车的总数
        Long count = this.redisTemplate.opsForHash().size(key);
        cartPage.setCount(count.intValue());
        //查询购物车的所有商品
        Map<String,Integer> entries = this.redisTemplate.opsForHash().entries(key);
        List<CookieCart> list = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : entries.entrySet()) {
            CookieCart cookieCart = new CookieCart();
            cookieCart.setAmount(entry.getValue());
            cookieCart.setProductId(Long.parseLong(entry.getKey()));
            list.add(cookieCart);
        }
        cartPage.setCartList(list);
        return cartPage;
    }

    /**
     * 合并登录用户和未登录时的所有购物车商品数据
     */
    @PostMapping("/mergeCart")
    public void mergeCart(Long userId){
        //获取未登录用户中的所有购物车数据
        String cartId = this.getCookiesCartId();
        String cookieKey = COOKIE_KEY + cartId;
        Map<String,Integer> entries = this.redisTemplate.opsForHash().entries(cookieKey);
        //将得到的购物车数据合并到登录用户的购物车中
        String userKey = CART_KEY + userId;
        this.redisTemplate.opsForHash().putAll(userKey,entries);
        //删除未登录用户的cookie购物车数据
        this.redisTemplate.delete(cookieKey);
        //删除未登录用户的cookie的cartId
        Cookie cookie = new Cookie("cartId",null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }


    public String getCookiesCartId() {
        //查看是否存在指定的cookie头
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("cartId")){
                    return cookie.getValue();
                }
            }
        }
        //没有，就创建一个cookie,生成一个全局id，并设置到cookie中
        Long id = this.idGenerator.incrementId();
        Cookie cookie = new Cookie("cartId",String.valueOf(id));
        response.addCookie(cookie);
        return id + "";
    }


}
